//
//  ChatingViewController.m
//  IOSTest
//
//  Created by Afluy on 14/12/28.
//  Copyright (c) 2014年 Afluy. All rights reserved.
//
/*
 NSLineBreakByWordWrapping = 0 //以空格为边界，保留单词。
 NSLineBreakByCharWrapping //保留整个字符
 NSLineBreakByClipping //简单剪裁，到边界为止
 NSLineBreakByTruncatingHead //前面部分文字以……方式省略，显示尾部文字内容
 NSLineBreakByTruncatingTail //结尾部分的内容以……方式省略，显示头的文字内容。
 NSLineBreakByTruncatingMiddle //中间的内容以……方式省略，显示头尾的文字内容。
 */

#import "ChatingViewController.h"
const float HEIGHT_TEXTFIELD = 40;
@interface ChatingViewController ()
{
    NSString* CELL_ID ;
    NSMutableArray* mData;
    UITableView* mTableView;
    CGFloat mAPPWidth;
    CGFloat mAPPHeight;
    UIFont *mFont;
    UITextField* textField ;
}
@end

@implementation ChatingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    CELL_ID = @"cell";
    mFont=[UIFont systemFontOfSize:14];
    mAPPWidth = [ UIScreen mainScreen ].applicationFrame.size.width;
    mAPPHeight = [ UIScreen mainScreen ].applicationFrame.size.height;
    NSLog(@"mAPPWidth: %f, mAPPHeight: %f",mAPPWidth,mAPPHeight);
    mTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, mAPPWidth, mAPPHeight-HEIGHT_TEXTFIELD+25)];
    [mTableView setDelegate:self];
    [mTableView setDataSource:self];
    [mTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:mTableView];

    textField = [[UITextField alloc]initWithFrame:CGRectMake(0, mTableView.frame.size.height, mAPPWidth-HEIGHT_TEXTFIELD,HEIGHT_TEXTFIELD)];
    [textField addTarget:self action:@selector(textFieldDidBeginEditing:) forControlEvents:UIControlEventEditingDidBegin];
    [textField addTarget:self action:@selector(textFieldDidEndEditing:) forControlEvents:UIControlEventEditingDidEnd];
    [self.view addSubview:textField];

    UIButton* sendBtn = [[UIButton alloc]initWithFrame:CGRectMake(textField.frame.size.width,mTableView.frame.size.height, (mAPPWidth-textField.frame.size.width),textField.frame.size.height)];
    [sendBtn setBackgroundColor:[UIColor blueColor]];
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(sendBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sendBtn];

  }
-(void)sendBtnClick:(UIButton*)btn{
    NSLog(@"click");
    [self sendText:textField.text];
}
-(void) refreshData:(NSMutableArray *)data {
    mData = data;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [mData count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SessionData *data = mData[indexPath.row];
    UIFont *font=[UIFont systemFontOfSize:14];
    CGSize size = [data.content sizeWithFont:font constrainedToSize:CGSizeMake(mAPPWidth/2, MAXFLOAT) lineBreakMode:NSLineBreakByClipping] ;
    NSLog(@"cell height: %f", size.height);
    return size.height+15;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    UITableViewCell *cell=(UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CELL_ID];
    UIFont *font;
    UIImageView *iconImg ;
    UILabel *label;
    UIImageView *labelBgView ;
    if(cell==nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CELL_ID];
        cell.selectionStyle=UITableViewCellStyleDefault;
        //头像
        iconImg =[[UIImageView alloc] initWithImage:nil];
        [iconImg setTag:0x001];
        //text
        label = [[UILabel alloc]initWithFrame:CGRectZero];
        [label setBackgroundColor:[UIColor clearColor]];
        label.font = mFont;
        label.numberOfLines= 0;
        label.lineBreakMode = NSLineBreakByCharWrapping;
        [label setTag:0x002];
        //text bg
        labelBgView = [[UIImageView alloc]initWithFrame:CGRectZero];
        [labelBgView setTag:0x003];
        //
        [cell.contentView addSubview:iconImg];
        [cell.contentView addSubview:labelBgView];
        [cell.contentView addSubview:label];
    }
    if(!iconImg){
        iconImg=(UIImageView*)[cell viewWithTag:0x001];
    }
    if (!label){
        label  = (UILabel*)[cell viewWithTag:0x002];
    }
    if(!labelBgView){
         labelBgView  = (UIImageView*)[cell viewWithTag:0x003];
    }
    
    SessionData *data = mData[indexPath.row];
    //头像
    [iconImg setImage:data.icon];
    iconImg.frame= CGRectMake(data.fromSelf ? (mAPPWidth-40):10, 10, 30, 30);
    //text
    //计算文件所占的长宽
    CGSize size = [data.content sizeWithFont:mFont constrainedToSize:CGSizeMake(mAPPWidth-100, MAXFLOAT) lineBreakMode:NSLineBreakByClipping];
    NSLog(@"%f,%f",size.width,size.height);   
    label.frame=CGRectMake(data.fromSelf ? (mAPPWidth-60-size.width):60, 15, size.width, size.height);
    label.text= data.content;
    
    //text bg 暂时找不到合适的图片，就先用纯色代替
//   UIImage *bubble =[UIImage imageNamed:data.fromSelf ? @"bubble_right":@"bubble_left"];
//   [labelBgView setImage:[bubble stretchableImageWithLeftCapWidth:floorf(bubble.size.width/2) topCapHeight:floorf(bubble.size.height/2)]];
    [labelBgView setBackgroundColor:data.fromSelf ?[UIColor brownColor]:[UIColor grayColor]];
    labelBgView.frame = CGRectMake(label.frame.origin.x - 10,label.frame.origin.y - 10,label.frame.size.width+20,label.frame.size.height+20);
    return cell;
}
-(void)sendText:(NSString*) text{
    if([text isEqualToString:@""]){
        return;
    }
    [textField setText:@""];//清空textField
    //模拟会话
    SessionData *data1=[[SessionData alloc]init];
    data1.fromSelf = YES;
//  data1.icon = iconImg;
    data1.content=text;
    data1.date= nil;
    [mData addObject:data1];
    [mTableView reloadData];
    
    //这里减去1 是因为TableView是从0计数的
    NSIndexPath* index = [NSIndexPath indexPathForRow:([mTableView numberOfRowsInSection:0]-1) inSection:0];
    
//  [mTableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionBottom animated:YES];
    [mTableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

/**
 下列代码是为了防止虚拟键盘弹出时遮挡了输入框
 */
-(void)textFieldDidBeginEditing:(UITextField *)textField{   //开始编辑时，整体上移
    [self moveView:-60];
}

-(void)textFieldDidEndEditing:(UITextField *)textField{     //结束编辑时，整体下移
    [self moveView:60];
}

-(void)moveView:(float)move{
    NSTimeInterval animationDuration = 0.30f;
    CGRect frame = self.view.frame;
    frame.origin.y += move;//view的X轴上移
    self.view.frame = frame;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];//设置调整界面的动画效果
    
}
@end
